#include"filterdata.h"
#include"webdownload.h"
#include<iostream>
#include<fstream>
#include<vector>
#include<regex>
using namespace std;

FilterData::FilterData()
{

}

FilterData::FilterData(const std::string& oldfilename,const std::string& newfilename):
    m_oldfilename(oldfilename),m_newfilename(newfilename)
{

}

FilterData::~FilterData()
{

}

void FilterData::DoMatchOSC()
{
    ifstream fin;
    fin.open(m_oldfilename,ios::in);
    ofstream fout;
    fout.open(m_newfilename,ios::out);
    string line;
    vector<string> list;
    do
    {
        fin>>line;
        regex reg("href=\"(.*)\"");
        smatch m;
        if(regex_match(line,m,reg))
        {
            cout<<m[1]<<endl;
            list.push_back(m[1]);
        }
    }while (!fin.eof());
    fin.close();

    cout<<"--------->:"<<endl;
    for(int i=0;i<(int)list.size();++i)
    {
        regex reg(".*/blog/[0-9]*");
        if(regex_match(list[i],reg))
        {
            cout<<list[i]<<endl;
            fout<<list[i]<<endl;
            string name=GetBlogName(list[i]);
            cout<<name<<endl;
            fout<<name<<endl;
        }
    }
    fout.close();
}

std::string FilterData::GetBlogName(const std::string& url)
{
    WebDownload::GetInstance()->GoDownload(url,"tmp.txt");
    ifstream fin;
    fin.open("tmp.txt",ios::in);
    int count=0;
    char buf[1024]={0};
    string line;
    regex reg(".*content=\"(.*)\".*");
    smatch m;
    int nbreak=0;
    do
    {
        fin.getline(buf,1024);
        line=buf;
        if(regex_match(line,m,reg))
        {
            count++;
        }
        if(count>6)
        {
            break;
        }
        ++nbreak;
        if(nbreak>2000)
        {
            break;
        }
    }while(!fin.eof());
    string tmp=m[1];
    return tmp==""?"无标题博客":tmp;
}
